﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Text;
using System.IO;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;
using InfoJetSoft.Service.ManagedCode;

namespace InfoJetSoft.Service.Worker
{
	
	class FormRunErrorConditionWorker
	{
		
		public static void  runErrorCondition(Form form)
		{
			bool alertNotSet = true;
			if( form.ValueChangeId == null )
			{
				//如果form.ValueChangeId为null,那么不需要设置ErrCondValiModalMessage.
				//只有值变化引起的postback才需要设置ErrCondValiModalMessage.
				alertNotSet = false;
			}
			
			XmlElement root = form.XmlDoc.DocumentElement;
			
			ArrayList errorConditionList = form.Manifest.ErrorConditionList;
			foreach (ErrorCondition errorCondition in errorConditionList)
			{
				List<XmlNode> matchNodes = XPathQuery.QueryErrorCondition(form, errorCondition);
                foreach (XmlNode xmlNode in matchNodes)
                {
                    string jetId = DOMUtil.getNodeJetId(xmlNode);
                    form.FieldErrorList.Add(new FieldError(FieldError.ConditionError, xmlNode, jetId, errorCondition.ShortMessage + "\n\n" + errorCondition.ErrorMessage));
                    //在ValueChange中,只显示ValueChangeNode上的ModalMessage,同时,只显示第一个ModalMessage.
                    if (alertNotSet && errorCondition.Type.Equals("modal"))
                    {
                        if (jetId.Equals(form.ValueChangeId))
                        {
                            form.ErrCondValiModalMessage = errorCondition.ShortMessage + "\n\n" + errorCondition.ErrorMessage;
                            alertNotSet = false;
                        }
                    }
                }
			}

            //CID 0858 //2011.03.29 //Begin
            foreach (ErrorBlank errorBlank in form.Manifest.ErrorBlankList)
            {
                XmlNodeList matchNodeList = DOMUtil.selectNodes(root, errorBlank.Match, 0, form.XmlNsResolver);
                foreach (XmlNode matchNode in matchNodeList)
                {
                    XmlNode contextNode = DOMUtil.selectANode(matchNode, errorBlank.ExpressionContext, form.XmlNsResolver);
                    if (contextNode != null)
                    {
                        bool result = XPathEvaluator.evaluateBooleanValue(form, contextNode, errorBlank.Expression);
                        if (result)
                        {
                            string jetId = DOMUtil.getNodeJetId(contextNode);
                            FieldError fieldError = new FieldError(FieldError.ConditionError, contextNode, jetId, "Cannot be blank.");
                            form.FieldErrorList.Add(fieldError);
                        }
                    }
                }
            }
            //CID 0858 //2011.03.29 //End
		}
	}
}